package com.shopcart.servlet;

import java.io.IOException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.shopcart.controller.CartController;
import com.shopcart.controller.CustomerController;
import com.shopcart.entity.Customer;

@WebServlet(name="LogoutServlet", urlPatterns={"/logout"})
public class LogoutServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public LogoutServlet() {
		super();
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException,
			IOException {
		CustomerController customerController = null;
		try {
			Context ctx = new InitialContext();
			customerController = (CustomerController) ctx
					.lookup("ejb/CustomerControllerBean");
		} catch (NamingException e) {
			System.err.println("Error getting bean!");
			e.printStackTrace();
		}
		HttpSession session = request.getSession();
		Customer customer = (Customer) session.getAttribute("customer");
		
		if (customer != null) {
			CartController cartContoller = (CartController) session.getAttribute("cartController");
			cartContoller.rollback();
			cartContoller.remove();
			
			session.invalidate();
			customerController.logoutCustomer(customer);
		}
		
		request.getRequestDispatcher("login.jsp").forward(request, response);
	}
}